package com.antler.smt.portal.config;

import com.antler.smt.entity.MemberEntity;
import com.antler.smt.entity.SysLogEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.annotation.OperateCut;
import com.antler.smt.portal.mapper.MemberEntityMapper;
import com.antler.smt.portal.mapper.SysLogEntityMapper;
import com.antler.smt.portal.utils.TokenUtil;
import com.antler.smt.response.base.Result;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 获取切面信息
 *
 * @author zhangyi
 * @date 2018/6/13 10:24
 */
@Aspect
@Component
public class SpringAopConfig {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Resource
    private MemberEntityMapper memberEntityMapper;

    @Resource
    private SysLogEntityMapper sysLogEntityMapper;

    /**
     * 用户操作内容
     */
    private StringBuffer operateContent = null;

    @Pointcut("@annotation(com.antler.smt.portal.annotation.OperateCut)")
    public void getAnnotationPointCut(){}

    @After("getAnnotationPointCut()")
    public void afterAnnotation(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperateCut annotation = method.getAnnotation(OperateCut.class);
        operateContent = new StringBuffer(annotation.operationContent());
        log.info("拦截注解:"+annotation.operationContent());
    }

    /**
     * 定义切点
     */
    @Pointcut("execution(* com.antler.smt.portal.controller..*.*(..))")
    public void exceutionService(){}

    /**
     * 执行方法之后织入
     *
     * @param joinPoint
     * @param returnValue
     */
    @AfterReturning(pointcut = "exceutionService()",returning = "returnValue")
    public void doAfterOperate(JoinPoint joinPoint, Object returnValue){

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        if(returnValue != null && operateContent != null)
        if (!returnValue.equals(null) &&  !operateContent.equals(null)){
            //创建系统日志实体
            SysLogEntity sysLogEntity = new SysLogEntity();
            //调用的方法
            String methodName = joinPoint.getSignature().getName();
            //获取用户请求的参数
            String params = Arrays.toString(joinPoint.getArgs());
            //当前用户的ip地址
            String localIp = getLocalIp(request);
            //获取当前用户信息
            MemberEntity localMember = getLocalMember(request);
            //用户名
            String userName = null;
            if(null != localMember) {
                Long userId = localMember.getId();
                MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(userId);
                if(memberEntity != null) {
                    String mobile = memberEntity.getMobile();
                    String email = memberEntity.getEmail();
                    if ("null".equals(mobile)) {
                        userName = email;
                    } else if ("null".equals(email)) {
                        userName = mobile;
                    } else {
                        userName = "暂无";
                    }
                }else{
                    userName = "暂无";
                }
            }
            sysLogEntity.setIp(localIp);
            sysLogEntity.setMethod(methodName);
            sysLogEntity.setParams(params);
            sysLogEntity.setMemberName(null == userName?"游客":userName);
            if(operateContent != null) {
                sysLogEntity.setOperationContent(operateContent.toString());
            }
            sysLogEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
            sysLogEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));
            int i = sysLogEntityMapper.insertSelective(sysLogEntity);
            Result result = new Result((i == 0) ? new Result(ResultCodeEnum.APPEND_DATA_ERROR):new Result(ResultCodeEnum.OPERATION_SUCCESS));
            log.info("成功获取用户请求",result);
            operateContent.delete(0,operateContent.length());
            //后期改为存入文件中 然后再定时插入到数据库中
        }
    }
    /**
     * 获取当前请求的IP地址
     *
     * @param request
     * @return
     */
    public static String getLocalIp(HttpServletRequest request) {

        String ip="";
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        }else{
            ip = request.getHeader("x-forwarded-for");
        }
        if(ip.length()>15){
            if(ip.indexOf(",")>0){
                ip = ip.substring(0,ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 获取cookie内保存的用户信息
     *
     * @param request
     * @return
     */
    public MemberEntity getLocalMember(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String token = null;
        if(null != cookies && 0 < cookies.length) {
            for (Cookie e : cookies) {
                if ("token".equals(e.getName())) {
                        token = e.getValue();
                        break;
                }
            }
        }
        if(token != null){
            return TokenUtil.getMemberByToken(token);
        }
        return null;
    }
}
